package com.house.service;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.house.dao.RepairMapper;
import com.house.entity.Order;
import com.house.entity.Repair;
import com.house.entity.User;
import com.house.util.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 订单模块服务层
 */
@Service
@Slf4j
public class RepairService extends ServiceImpl<RepairMapper, Repair> {


    @Autowired
    private OrderService orderService;


    public boolean saveOrUpdate(Repair repair) {
        if(StrUtil.isEmpty(repair.getId())) {
            repair.init();
            repair.setStatus("0");


            // 填充登录用户信息
            User user = LoginUtil.getLoginUser();
            repair.setCreateUser(user.getId());
            repair.setUsername(user.getUsername());

            // 根据订单信息ID 查询房屋ID
            Order order = orderService.getById(repair.getOrderId());
            repair.setTitle(order.getTitle());
            repair.setHouseId(order.getHouseId());
        } else {
            repair.setUpdateTime(DateUtil.now());

            // 如果状态更新为已完成， 更新完成时间为当前时间
            Repair oldRepair = super.getById(repair.getId());
            if("2".equals(repair.getStatus()) && !"2".equals(oldRepair.getStatus())) {
                repair.setCompletionTime(DateUtil.now());
            }
        }

        return super.saveOrUpdate(repair);
    }
}
